import { h } from 'vue';

import { setupVbenVxeTable, useVbenVxeGrid } from '@vben/plugins/vxe-table';
import { formatDateTime } from '@vben/utils';

import { Avatar, Button, Image, Switch, Tag } from 'ant-design-vue';

import userAvatar from '#/assets/user.gif';
import Upload from '#/components/Upload';

import { useVbenForm } from './form';

setupVbenVxeTable({
  configVxeTable: (vxeUI) => {
    vxeUI.setConfig({
      grid: {
        align: 'center',
        border: false,
        columnConfig: {
          resizable: true,
        },
        minHeight: 300,
        formConfig: {
          // 全局禁用vxe-table的表单配置，使用formOptions
          enabled: false,
        },
        proxyConfig: {
          autoLoad: true,
          response: {
            result: 'list',
            total: 'total',
            list: 'list',
          },
          showActiveMsg: true,
          showResponseMsg: false,
        },
        round: true,
        showOverflow: true,
        size: 'small',
      },
      pager: {
        pageSize: 10,
      },
    });

    // 表格配置项可以用 cellRender: { name: 'CellImage' },
    vxeUI.renderer.add('CellImage', {
      renderTableDefault(_renderOpts, params) {
        const { column, row } = params;
        return h(Image, {
          src: row[column.field],
          width: '40px',
        });
      },
    });

    vxeUI.renderer.add('CellAvatar', {
      renderTableDefault(_renderOpts, params) {
        const { column, row } = params;
        const avatar = row[column.field] || userAvatar;
        return h(Avatar, { src: avatar });
      },
    });

    // 表格配置项可以用 cellRender: { name: 'CellLink' },
    vxeUI.renderer.add('CellLink', {
      renderTableDefault(renderOpts) {
        const { props } = renderOpts;
        return h(
          Button,
          { size: 'small', type: 'link' },
          { default: () => props?.text },
        );
      },
    });

    // 表格配置项可以用 cellRender: { name: 'CellLink' },
    vxeUI.renderer.add('CellStatus', {
      renderTableDefault(renderOpts, params) {
        const { props, column, row } = { ...renderOpts, ...params };
        // 解构传入的 `props`，并将事件回调合并
        const { on, ...restProps } = props || {};
        // 将 `onChange` 事件处理器传入 `Switch` 组件
        return h(Switch, {
          ...restProps,
          checked: row[column.field],
          onChange: (checked) => {
            // 在这里可以执行额外的逻辑或调用回调
            if (on && typeof on.change === 'function') {
              on.change(checked, row, column);
            }
          },
        });
      },
    });

    vxeUI.renderer.add('CellUserStatus', {
      renderTableDefault(renderOpts, params) {
        const { props, column, row } = { ...renderOpts, ...params };
        // 解构传入的 `props`，并将事件回调合并
        const { ...restProps } = props || {};
        const userStatusObj: any = { 0: '禁用', 1: '启用', 2: '未验证' };
        const value = row[column.field];
        const color = [0, 2].includes(value) ? 'default' : 'success';
        const text = userStatusObj[value];
        return h(
          Tag,
          {
            ...restProps,
            color,
          },
          { default: () => text },
        );
      },
    });

    vxeUI.renderer.add('CellUser', {
      renderTableDefault(renderOpts, params) {
        const { props, column, row } = { ...renderOpts, ...params };
        // 解构传入的 `props`，并将事件回调合并
        const { ...restProps } = props || {};
        const user: any = row[column.field];
        const userId = user?.id ?? row.user_id;

        const text = user ? `${user.user_nickname}-(ID:${userId})` : '-';
        return h(
          Tag,
          {
            ...restProps,
          },
          { default: () => text },
        );
      },
    });

    vxeUI.renderer.add('CellUpload', {
        renderTableDefault(renderOpts, params) {
          const { props, row, column } = { ...renderOpts, ...params };
          const { ...restProps } = props || {};

          return h(Upload, {
            ...restProps,
            modelValue: row[column.property],               // 绑定值
            'onUpdate:modelValue': (val) => {  
              row[column.property] = val;
              params.$table.reloadRow(row);
              params.$table.dispatchEvent('editClosed', {
                  row,
                  rowIndex: params.rowIndex,
                });
           
            },
            ucClass: 'table-uploader',
          });
        },
    });


    // 这里可以自行扩展 vxe-table 的全局配置，比如自定义格式化
    // vxeUI.formats.add

    vxeUI.formats.add('formatShortDateTime', {
      tableCellFormatMethod({ cellValue }) {
        return cellValue ? formatDateTime(cellValue * 1000) : '-';
      },
    });
  },
  useVbenForm,
});

export { useVbenVxeGrid };

export type * from '@vben/plugins/vxe-table';
